#include "backuprecorditem.h"
#include "ui_backuprecorditem.h"
#include "web/file_download.pb.h"

BackupRecordItem::BackupRecordItem(QWidget *parent, FileInfo info)
    : QWidget(parent)
    , ui(new Ui::BackupRecordItem)
{
    ui->setupUi(this);

    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_downloadFinished, this, &BackupRecordItem::updateStatus);
}

BackupRecordItem::~BackupRecordItem()
{
    delete ui;
}

void BackupRecordItem::setSelected(bool selected)
{
    if (m_isSelected != selected) {
        m_isSelected = selected;
        ui->checkBox->setChecked(selected);
        emit selectionChanged(selected);
    }
}

void BackupRecordItem::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    // 根据悬浮状态选择颜色
    QColor bgColor = m_isHovered ? QColor(0xf8, 0xf8, 0xf8) : QColor(255, 255, 255);
    painter.fillRect(rect(),  bgColor);

    QWidget::paintEvent(event);
}

void BackupRecordItem::enterEvent(QEnterEvent *event)
{
    m_isHovered = true;
    update();  // 触发重绘
    QWidget::enterEvent(event);
}

void BackupRecordItem::leaveEvent(QEvent *event)
{
    m_isHovered = false;
    update();  // 触发重绘
    QWidget::leaveEvent(event);
}

void BackupRecordItem::on_DownloadBtn_clicked()
{
    if(m_isDownloaded){
        //ui提示已经上传过了
        ui->DownloadBtn->setEnabled(false);
        return;
    }

    // 1. 构建下载请求（仅需file_id）
    file_download::FileDownloadReq req;
    req.set_file_id(m_recordFileInfo.fileId);
    QByteArray data(req.SerializeAsString().data(), req.ByteSizeLong());

    emit attemptToDownload();

    // 2. 发送请求并记录上下文（用于响应关联）
    emit TcpMgr::GetInstance()->sig_sendDownloadRequest(data, m_recordFileInfo);

    // 3. 临时禁用按钮
    ui->DownloadBtn->setText("下载中...");
    ui->DownloadBtn->setEnabled(false);
}


void BackupRecordItem::on_DeleteBtn_clicked()
{
    //暂时不实现
    //emit deleteThisRecord(this);
}


void BackupRecordItem::on_checkBox_clicked()
{
    m_isSelected = ui->checkBox->isChecked();
    emit selectionChanged(m_isSelected);
}

void BackupRecordItem::updateStatus(int file_id)
{
    if(file_id == m_recordFileInfo.fileId){
        ui->DownloadBtn->setEnabled(true);
    }
}

